package com.waimai1.waimai.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.waimai1.waimai.common.BaseContext;
import com.waimai1.waimai.dao.UserDao;
import com.waimai1.waimai.entity.Acid;
import com.waimai1.waimai.entity.MyOrder;
import com.waimai1.waimai.entity.User;
import com.waimai1.waimai.exception.EnumException;
import com.waimai1.waimai.exception.NotErrorException;
import com.waimai1.waimai.service.AcidService;
import com.waimai1.waimai.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.Date;

/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2023-09-24 17:30:11
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {
//    @Value("${wxPay.appid}")
//    private String appid;
//    @Value("${wxPay.secret}")
//    private String secret;
    @Autowired
    private AcidService acidService;
    @Override
    public User getUserInfo(String code) {
//
        int acid=BaseContext.getAcid();
        Acid resAcid=acidService.getById(BaseContext.getAcid());

//        http接口调用web
        String url="https://api.weixin.qq.com/sns";
        WebClient webClient = WebClient.builder().baseUrl(url).defaultHeader("Content-Type", "text/plain")
                .build();
        Mono<String> result = webClient.get()
                .uri("/jscode2session?appid={appid}&secret={secret}&js_code={code}&grant_type=authorization_code",resAcid.getAppid(),resAcid.getSecret(),code)
                .accept(MediaType.TEXT_PLAIN)
                .header("Content-Type", "text/plain")
                .retrieve()
                .bodyToMono(String.class);
        Object resObj = result.block();
        assert resObj != null;
        JSONObject json=JSONObject.parseObject(resObj.toString());
        if(json.containsKey("errcode")){
            throw new NotErrorException(Integer.parseInt(json.getString("errcode")),json.getString("errmsg"));
        }
        String openid=json.getString("openid");
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getAcid,BaseContext.getAcid()).eq(openid != null, User::getOpenid, openid);
        User userInfo= this.getOne(queryWrapper,false);
        if(userInfo==null){
            //不存在则注册
            User userInfo1=new User();
            userInfo1.setName("用户"+String.valueOf(new Date().getTime()).substring(8));
            userInfo1.setStatus("启用");
            userInfo1.setOpenid(openid);
            userInfo1.setAcid(BaseContext.getAcid());
            if(!this.save(userInfo1)){
                throw new NotErrorException(EnumException.NO_SAVE_USER);
            }
            return this.getOne(queryWrapper);
        }
        return userInfo;
    }
    @Override
    public User getUserByOpenid(){
        LambdaQueryWrapper<User> userLambdaQueryWrapper=new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getOpenid, BaseContext.getopenId())
        .eq(User::getAcid,BaseContext.getAcid());
        User userRes= this.getOne(userLambdaQueryWrapper,false);
        if(null==userRes){
            throw new NotErrorException(EnumException.NO_USER);
        }
        return userRes;
    }
    @Override
    public void updatePhone(MyOrder order){
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getOpenid,order.getOpenid())
                .eq(User::getAcid, BaseContext.getAcid());
        User user=new User();
        user.setOpenid(order.getOpenid());
        user.setPhone(order.getTakePhone());
        this.update(user,queryWrapper);
    }
}

